// 导航守卫
// 导入路由
import router from '@/router'
// 导入store获取token
import store from '@/store'
// 虚拟进度条
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'
const whitePage = ['/404', '/login']
// 前置导航守卫
router.beforeEach((to, from, next) => {
  // 进度条启用
  Nprogress.start()
  // 获取token
  const token = store.state.user.token
  const userId = store.state.user.userInfo.userId
  // 携带token
  if (token) {
    // 进入的是登录页,跳转至首页
    if (to.path.toLocaleLowerCase() === '/login') {
      next('/')
    } else {
      if (userId) {
        next()
      } else {
        store.dispatch('user/getUserInfo')
        next()
      }
    }
  } else {
    if (whitePage.includes(to.path.toLocaleLowerCase())) {
      next()
    } else {
      next('/login?redirect=' + to.fullPath)
    }
  }
  // 进度条结束
  Nprogress.done()
})

// 后置导航守卫
router.afterEach((to, from) => {
  // 进度条结束
  Nprogress.done()
})
